import React, { useEffect } from 'react'
import { Layout, Tabs } from 'antd'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useAppDispatch, useAppNavigation } from '@/hooks'
import type { TPanes } from '@/store/slice/siderCommon'
import { addPanes, removePanes, useSelectorsiderCommon } from '@/store/slice/siderCommon'

const { Content } = Layout
const { TabPane } = Tabs

function IndexContent() {
    const dispatch = useAppDispatch()
    const navigate = useNavigate()
    const { panes } = useSelectorsiderCommon()
    const { subTitle } = useAppNavigation()
    const { pathname } = useLocation()
    useEffect(() => {
        // 添加tabs
        dispatch(
            addPanes({
                title: subTitle,
                key: pathname,
                closable: true
            })
        )
    }, [pathname])
    return (
        <Content style={{ margin: '5PX' }}>
            <div className="site-layout-background" style={{ padding: 5, height: '100%' }}>
                <Tabs
                    type="editable-card"
                    hideAdd={true}
                    // 切换面板的回调
                    onChange={(activeKey) => {
                        navigate(activeKey)
                    }}
                    // 当前激活 tab 面板的 key
                    activeKey={pathname}
                    //新增和删除页签的回调，在 type="editable-card" 时有效
                    onEdit={(actionKey, action) => {
                        if (action === 'remove') {
                            const index = panes.findIndex((v: TPanes) => v.key === actionKey)
                            if (index > 0) {
                                dispatch(removePanes(index)) // 删除
                                // 如果点击的是关闭当前标签（已选中）
                                if (actionKey === pathname) navigate(panes[index - 1].key) // 跳转
                            }
                        }
                    }}
                >
                    {panes.map((pane: TPanes) => (
                        <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                            {pathname === pane.key && <Outlet />}
                        </TabPane>
                    ))}
                </Tabs>
            </div>
        </Content>
    )
}

export default IndexContent
